//
//  KnowledgeDetailViewController.m
//  Grammar
//
//  Created by Rick on 6/29/13.
//
//

#import "KnowledgeDetailViewController.h"
#import "DetailHeaderView.h"
#import "TeachKnowledgeCell.h"
#import "ITTXibViewUtils.h"
#import "AppDelegate.h"
#import "ITTImageZoomableView.h"
#import "ITTPullTableView.h"
#import "NoteBookManager.h"
#import "Note.h"
#import <MediaPlayer/MediaPlayer.h>
#import <CoreMedia/CoreMedia.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "NoteBookCell.h"
#import "ITTImageZoomableView.h"
#import "KnowledgeManager.h"
#import "ITTImageCacheManager.h"
#import "Grammar.h"
#import "GetExplainDataRequest.h"
#import "GrammarExplain.h"
#import "GrammarManager.h"
#import "ExplainManager.h"
#import "SyncGrammarExplainDataRequest.h"
#import "UpdateStudyPlanDataRequest.h"
#import "AddNoteDataRequest.h"
#import "DeleteNoteBookDataRequest.h"
#import "CircularProgressView.h"

#define GET_EXPLAIN_DATA_REQUEST    @"GET_EXPLAIN_DATA_REQUEST"
#define SYNC_EXPLAIN_DATA_REQUEST   @"SYNC_EXPLAIN_DATA_REQUEST"

@interface KnowledgeDetailViewController ()<UITextFieldDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITableViewDataSource,UITableViewDelegate,ITTImageZoomableViewDelegate,ITTPullTableViewDelegate,ITTImageZoomableViewDelegate,DetailHeaderViewDelegate,TeachKnowledgeCellDelegate,NoteBookCellDelegate,UIGestureRecognizerDelegate,UIActionSheetDelegate>
{
    DetailTableViewStyle _tableViewType;
    NSUInteger _selectedSection;
    NSMutableArray *_teachArray;
    TeachKnowledgeCell *_teachKnowledgeCell;
    CGFloat _currentRowHeight;
    NSMutableArray *_noteArray;
    Note *_currentNoteBook;
    BOOL _isCaptured;
    UIView *_bgView;
    NSInteger _deleteIndex;
    
}
@property (retain, nonatomic) IBOutlet UILabel *hintLabel;
@property (retain, nonatomic) IBOutlet UIImageView *chooseImageView;
@property (retain, nonatomic) IBOutlet UIButton *noteButton;
@property (retain, nonatomic) IBOutlet ITTPullTableView *detailTableView;
@property (retain, nonatomic) IBOutlet UIView *updateHintView;
@property (retain, nonatomic) IBOutlet UIView *contentView;
@property (retain, nonatomic) IBOutlet UIView *addNoteView;
@property (retain, nonatomic) IBOutlet UITextField *noteTextField;
@property (retain, nonatomic) IBOutlet UIButton *camerButton;
@property (retain, nonatomic) IBOutlet UILabel *titleLabel;

@end

@implementation KnowledgeDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self showUpdateView];
    
    if (isReachability) {
        [self checkUpdateState];
    }else {
        [self noNetWorkState];
    }
    
    [_detailTableView setRefreshViewHidden:NO];
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    tapGestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:tapGestureRecognizer];
    [tapGestureRecognizer release];
    
    
    _tableViewType = DetailTableViewStyleTeach;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, SCREEN_HEIGHT)];
    _bgView.alpha = 1;
    _bgView.backgroundColor = [UIColor blackColor];
    
    //initknowledgeArray
    
    [_detailTableView setLoadMoreViewHidden:YES];
    [_detailTableView setPullBackgroundColor:[UIColor colorWithRed:245/255.0 green:242/255.0 blue:238/255.0 alpha:1]];
    
    _noteArray = [[NSMutableArray alloc] init];
    _currentNoteBook = [[Note alloc] init];
    _currentNoteBook.grammarId = _currentGrammar.grammarId;
    _currentNoteBook.content = @"";
    _currentNoteBook.image = @"";
    
    [ExplainManager sharedManager].grammarId = _currentGrammar.grammarId;
    _teachArray = [[NSMutableArray alloc] initWithArray:[ExplainManager sharedManager].grammarExplains];
    if ([_teachArray count] == 0) {
        [self getExplainDataRequest];
    }else {
        [self checkUpdate];
       [_detailTableView reloadSections:[NSIndexSet indexSetWithIndex:0]withRowAnimation:UITableViewRowAnimationFade];
    }
    _titleLabel.text = _currentGrammar.title;
    _selectedSection = [_teachArray count];
    
    
    [self updateNoteButton];
}
- (void)checkUpdate
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];

    [parameters setObject:_currentGrammar.grammarId forKey:@"grammarId"];
    
//    if ([[DataCacheManager sharedManager] getCachedObjectByKey:[NSString stringWithFormat:@"CREATE_TIME_%@",_currentGrammar.grammarId]]) {
//        [parameters setObject:[[DataCacheManager sharedManager] getCachedObjectByKey:[NSString stringWithFormat:@"CREATE_TIME_%@",_currentGrammar.grammarId]] forKey:@"maxUpdateTime"];
//    }else {
//        
//    }
    NSString *maxUpdateTime = @"";
    for (GrammarExplain *aExplain in _teachArray) {
        if ([maxUpdateTime intValue] <[aExplain.lastUpdateTimeStamp intValue]) {
            maxUpdateTime = aExplain.lastUpdateTimeStamp;
        } 
    }
    [parameters setObject:maxUpdateTime forKey:@"maxUpdateTime"];
    [parameters setObject:@"1" forKey:@"action"];
    [SyncGrammarExplainDataRequest requestWithParameters:parameters withIndicatorView:nil withCancelSubject:nil onRequestStart:nil onRequestFinished:^(ITTBaseDataRequest *request) {
        
        if ([[request.resultDic objectForKey:@"haveUpdate"] intValue] != 0) {
            if (_tableViewType == DetailTableViewStyleTeach) {
//                [self showUpdateView];
                [self syncUpdateState];
                [_detailTableView setRefreshViewHidden:NO];
            }
        }else {
            [self haveNoNewestUpdate];
        }
        
    } onRequestCanceled:^(ITTBaseDataRequest *request) {
        
    } onRequestFailed:^(ITTBaseDataRequest *request) {
        [self noNetWorkState];
    }];
}
- (void)syncExplainDataRequest
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    NSString *wholeString = (NSString*)[[DataCacheManager sharedManager] getCachedObjectByKey:WHOLE_VERSION];
    if (wholeString) {
        [parameters setObject:wholeString forKey:@"wholeVersion"];
    }else {
        [parameters setObject:@"1" forKey:@"wholeVersion"];
    }
    [parameters setObject:_currentGrammar.grammarId forKey:@"grammarId"];
    if ([[DataCacheManager sharedManager] getCachedObjectByKey:[NSString stringWithFormat:@"CREATE_TIME_%@",_currentGrammar.grammarId]]) {
        [parameters setObject:[[DataCacheManager sharedManager] getCachedObjectByKey:[NSString stringWithFormat:@"CREATE_TIME_%@",_currentGrammar.grammarId]] forKey:@"maxUpdateTime"];
    }else {
        [parameters setObject:@"1" forKey:@"maxUpdateTime"];
    }
    
    [parameters setObject:@"0" forKey:@"action"];
    
    
    [SyncGrammarExplainDataRequest requestWithParameters:parameters withIndicatorView:nil withCancelSubject:nil onRequestStart:^(ITTBaseDataRequest *request) {
        
    } onRequestFinished:^(ITTBaseDataRequest *request) {
        
        [self haveNoNewestUpdate];
        
        [self refreshDataDone];
        [self loadMoreDataDone];
        if ([request.resultDic objectForKey:@"syncFind"]) {

            for (NSDictionary *explainDic  in [request.resultDic objectForKey:@"syncFind"]) {
                GrammarExplain *aGrammarExplain = [[GrammarExplain alloc] initWithDataDic:explainDic];
                [[DataCacheManager sharedManager] addObject: aGrammarExplain.lastUpdateTimeStamp  forKey:[NSString stringWithFormat:@"CREATE_TIME_%@",_currentGrammar.grammarId]];
                [ExplainManager sharedManager].grammarId = _currentGrammar.grammarId;
                [[ExplainManager sharedManager] addGrammarExplain:aGrammarExplain];
                
                [aGrammarExplain release];
            }
        }
        
        
        if ([request.resultDic objectForKey:@"syncDelete"]) {
            
            for (NSDictionary *explainDic  in [request.resultDic objectForKey:@"syncDelete"]) {
                GrammarExplain *aGrammarExplain = [[GrammarExplain alloc] initWithDataDic:explainDic];
                [[DataCacheManager sharedManager] addObject: aGrammarExplain.lastUpdateTimeStamp  forKey:[NSString stringWithFormat:@"CREATE_TIME_%@",_currentGrammar.grammarId]];
                [ExplainManager sharedManager].grammarId = _currentGrammar.grammarId;
                [[ExplainManager sharedManager] removeGrammarExplain:aGrammarExplain];
                [aGrammarExplain release];
            }
        }
        
        if ([request.resultDic objectForKey:@"syncUpdate"]) {
            for (NSDictionary *explainDic  in [request.resultDic objectForKey:@"syncUpdate"]) {
                GrammarExplain *aGrammarExplain = [[GrammarExplain alloc] initWithDataDic:explainDic];
                [[DataCacheManager sharedManager] addObject: aGrammarExplain.lastUpdateTimeStamp  forKey:[NSString stringWithFormat:@"CREATE_TIME_%@",_currentGrammar.grammarId]];
                [ExplainManager sharedManager].grammarId = _currentGrammar.grammarId;
                [[ExplainManager sharedManager] updateGrammarExplain:aGrammarExplain];
                [aGrammarExplain release];
            }
        }
        
        _currentGrammar.creteTimeStamp = [NSString stringWithFormat:@"%f",[request.requestStartTime timeIntervalSince1970]] ;
        [GrammarManager sharedManager].grammarType = @"normal";
        [[GrammarManager sharedManager] updateGrammar:_currentGrammar];
        
        [ExplainManager sharedManager].grammarId = _currentGrammar.grammarId;
        if (_teachArray) {
            RELEASE_SAFELY(_teachArray);
        }
        _teachArray = [[NSMutableArray alloc] initWithArray:[ExplainManager sharedManager].grammarExplains];
        [_detailTableView reloadData];
        
    } onRequestCanceled:^(ITTBaseDataRequest *request) {
        [self refreshDataDone];
        [self loadMoreDataDone];
    } onRequestFailed:^(ITTBaseDataRequest *request) {
        [self refreshDataDone];
        [self loadMoreDataDone];
    }];
}
#pragma mark - Hide Keyboard
- (void)hideKeyBoard
{
    [_noteTextField resignFirstResponder];
    
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    //Touch gestures below top bar should not make the page turn.
    //EDITED Check for only Tap here instead.
    if ([touch.view isKindOfClass:[UIButton class]] || [touch.view isKindOfClass:[UITextField class]] || [touch.view isKindOfClass:[ITTImageZoomableView class]]) {
        return NO;
    }
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void)getExplainDataRequest
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:_currentGrammar.grammarId forKey:@"grammarId"];
    [GetExplainDataRequest requestWithParameters:parameters withIndicatorView:nil withCancelSubject:nil onRequestStart:nil onRequestFinished:^(ITTBaseDataRequest *request) {
        [self haveNoNewestUpdate];
        [self refreshDataDone];
        [self loadMoreDataDone];
        
        for (NSDictionary *explainDic  in [request.resultDic objectForKey:@"explainList"]) {
            GrammarExplain *aGrammarExplain = [[GrammarExplain alloc] initWithDataDic:explainDic];
            [ExplainManager sharedManager].grammarId = _currentGrammar.grammarId;
            [[ExplainManager sharedManager] addGrammarExplain:aGrammarExplain];
            
            [aGrammarExplain release];
        }
        if (_teachArray) {
            RELEASE_SAFELY(_teachArray);
        }
        _teachArray = [[NSMutableArray alloc] initWithArray:[ExplainManager sharedManager].grammarExplains];
        [_detailTableView reloadData];
    } onRequestCanceled:^(ITTBaseDataRequest *request) {
        [self refreshDataDone];
        [self loadMoreDataDone];
        
    } onRequestFailed:^(ITTBaseDataRequest *request) {
        [self refreshDataDone];
        [self loadMoreDataDone];
    }];
}

- (void)updateNoteButton
{
    [NoteBookManager sharedManager].gramarId = _currentGrammar.grammarId;
    [_noteButton setTitle:[NSString stringWithFormat:@"笔记本[%d]",[[NoteBookManager sharedManager].notes count]] forState:UIControlStateNormal];
    [_noteButton setTitle:[NSString stringWithFormat:@"笔记本[%d]",[[NoteBookManager sharedManager].notes count]] forState:UIControlStateHighlighted];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_noteTextField resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    [[ITTImageCacheManager sharedManager] clearMemoryCache];
//    [[ITTImageCacheManager sharedManager] clearDiskCache];
}

- (void)unloadedView
{
    [self setNoteButton:nil];
    [self setDetailTableView:nil];
    [self setUpdateHintView:nil];
    [self setContentView:nil];
    [self setChooseImageView:nil];
    [self setAddNoteView:nil];
    [self setNoteTextField:nil];
    [self setCamerButton:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate shareAppdelegate].homeTabbarController hideTabBarAnimated:YES];
    _detailTableView.height = SCREEN_HEIGHT-130;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:self];
    [_currentGrammar release];
    [_currentNoteBook release];
    [_noteArray release];
    [_teachArray release];
    [_teachKnowledgeCell release];
    [_noteButton release];
    [_detailTableView release];
    [_updateHintView release];
    [_contentView release];
    [_chooseImageView release];
    [_addNoteView release];
    [_noteTextField release];
    [_camerButton release];
    [_titleLabel release];
    [_hintLabel release];
    [_loadActivityIndicator release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self unloadedView];
    [self setTitleLabel:nil];
    [self setHintLabel:nil];
    [self setLoadActivityIndicator:nil];
    [super viewDidUnload];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated]  ;
    DATA_ENV.isLoadKnowledge = NO;
    [_noteTextField resignFirstResponder];
    [[NSNotificationCenter defaultCenter] postNotificationName:SYNC_EXPLAIN_DATA_REQUEST object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:GET_EXPLAIN_DATA_REQUEST object:nil];
}

- (void)switchTableViewType:(DetailTableViewStyle)type
{
    if (type == _tableViewType) {
        return;
    }else {
        _tableViewType = type;
    }
    
    
    if (type == DetailTableViewStyleTeach) {
        [UIView animateWithDuration:0.3 animations:^{
            _chooseImageView.left = 0;
        }];
         _detailTableView.height = SCREEN_HEIGHT-130;
        [_detailTableView setRefreshViewHidden:NO];
                
        [_detailTableView setLoadMoreViewHidden:YES];
        [self hideAddNoteView];
        [self showUpdateView];
    }else if (type == DetailTableViewStyleNote) {
        [UIView animateWithDuration:0.3 animations:^{
            _chooseImageView.left = 160;
        }];

        [_detailTableView setRefreshViewHidden:YES];
        [_detailTableView setLoadMoreViewHidden:YES];
        _detailTableView.height = SCREEN_HEIGHT-110;
        [self hideUpdateView];
        [self showAddNoteView];
    }
    
    [_detailTableView reloadData];
}

- (void)showUpdateView
{
    _updateHintView.top = 40;
    [UIView animateWithDuration:0.3 animations:^{
        _updateHintView.alpha = 1;
    }];
    [_contentView addSubview:_updateHintView];
    
    
    _detailTableView.top = 60;
    
}

- (void)checkUpdateState
{
    _loadActivityIndicator.hidden = NO;
    _hintLabel.text = @"正在检查同步...";
}

- (void)haveNoNewestUpdate
{
    _loadActivityIndicator.hidden = YES;
    _hintLabel.text = @"已是最新数据";
}

- (void)syncUpdateState
{
    _loadActivityIndicator.hidden = YES;
    _hintLabel.text = @"讲解有更新，下拉更新";
}

- (void)updateNowState
{
    _loadActivityIndicator.hidden = NO;
    _loadActivityIndicator.left = 12;
    _hintLabel.text = @"正在更新...";
}

- (void)noNetWorkState
{
    _loadActivityIndicator.hidden = YES;
    _hintLabel.text = @"离线模式,无法更新,请检查网络";
}

- (void)hideUpdateView
{
    [UIView animateWithDuration:0.3 animations:^{
        _updateHintView.alpha = 0;
    }];
    [_updateHintView removeFromSuperview];
    _detailTableView.top = 40;
}

- (void)showAddNoteView
{
    _detailTableView.height = SCREEN_HEIGHT-150;
    [UIView animateWithDuration:0.3 animations:^{
        _addNoteView.alpha = 1;
        _addNoteView.top = _detailTableView.bottom;
    } completion:^(BOOL finished) {
        [_contentView addSubview:_addNoteView];
        _detailTableView.top = 40;
    }];
}

- (void)hideAddNoteView
{
    
    _detailTableView.height = SCREEN_HEIGHT-110;
    
    [UIView animateWithDuration:0.3 animations:^{
        _addNoteView.alpha = 0;
        _addNoteView.top = _detailTableView.bottom;
    } completion:^(BOOL finished) {
        [_addNoteView removeFromSuperview];
    }];
    
    
}

#pragma mark - Keyboard
- (void)keyboardWillShow:(NSNotification *)notification
{
//    static CGFloat normalKeyboardHeight = 216.0f;
    
    NSDictionary *info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    CGFloat distanceToMove = kbSize.height;
    [UIView animateWithDuration:0.3 animations:^{
        _addNoteView.bottom = SCREEN_HEIGHT-70- distanceToMove;
    }];
    //自适应代码
}
#pragma mark - IBAction
- (IBAction)tapBackButton:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (IBAction)tapTeachButton:(id)sender {
    [self switchTableViewType:DetailTableViewStyleTeach];
}

- (IBAction)tapNoteButton:(id)sender {
    [self switchTableViewType:DetailTableViewStyleNote];
}
- (IBAction)tapKeepNoteButton:(id)sender {
    _currentNoteBook.content = _noteTextField.text;
    [self addNote];
}
- (IBAction)tapCamerButton:(id)sender {
    if (_isCaptured) {
        // enlarge the image;
        [self enlargeTheImage:_currentNoteBook];
    }else {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"手机拍照",@"从相册取照片", nil];
        actionSheet.tag = 1200;
        [actionSheet showInView:self.view];
        [actionSheet release];
    }
    
    
    
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 1200) {
        switch (buttonIndex) {
            case 0:
            {
                //showCameraCaptureView
                [self showCameraCaptureViewWithType:UIImagePickerControllerSourceTypeCamera];
            }
                break;
            case 1:
            {
                //showCameraCaptureView
                [self showCameraCaptureViewWithType:UIImagePickerControllerSourceTypePhotoLibrary];
            }
                break;
                
            default:
                break;
        }

    }
    
    if (actionSheet.tag == 1100) {
        switch (buttonIndex) {
            case 0:
            {
                //删除
//                [_detailTableView beginUpdates];
                [NoteBookManager sharedManager].gramarId = _currentGrammar.grammarId;
                [NoteBookManager sharedManager].gramarId = _currentGrammar.grammarId;
                ITTDINFO(@" index ..... %d",_deleteIndex);
//                _detailTableView.
                
                [[NoteBookManager sharedManager] removeNote:[[NoteBookManager sharedManager].notes objectAtIndex:_deleteIndex]];
                [_detailTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:_deleteIndex inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                [self updateNoteButton];
                [_detailTableView reloadData];
                if ([_noteArray count] == 0) {
                    [GrammarManager sharedManager].grammarType = @"archive";
                    [[GrammarManager sharedManager] removeGrammar:_currentGrammar];
                    [GrammarManager sharedManager].grammarType = @"review";
                    [[GrammarManager sharedManager] removeGrammar:_currentGrammar];
                }
                
//                NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
//                [parameters setObject:@"" forKey:@"uid"];
//                [parameters setObject:@"" forKey:@"uid"];
//                [DeleteNoteBookDataRequest requestWithParameters:parameters withIndicatorView:nil withCancelSubject:nil onRequestStart:nil onRequestFinished:^(ITTBaseDataRequest *request) {
//                    
//                } onRequestCanceled:^(ITTBaseDataRequest *request) {
//                    
//                } onRequestFailed:^(ITTBaseDataRequest *request) {
//                    
//                }];
//                [_detailTableView endUpdates];
            }
                break;
            case 1:
            {
                //showCameraCaptureView
//                [self showCameraCaptureViewWithType:UIImagePickerControllerSourceTypePhotoLibrary];
            }
                break;
                
            default:
                break;
        }
    }
}

#pragma mark - UIImage
- (void)enlargeTheImage:(Note*)noteBook
{    
    [self.view addSubview:_bgView]; 
    ITTImageZoomableView *zoomView = [[[ITTImageZoomableView alloc] initWithFrame:self.view.bounds] autorelease];
    zoomView.alpha = 0;
    zoomView.tapDelegate = self;
    [zoomView displayImage:((ITTImageInfo*)noteBook.image)];
    [self.view addSubview:zoomView];
    
    [UIView animateWithDuration:0.3f animations:^{
        zoomView.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)addNote
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *dateStr = [dateFormatter stringFromDate:[NSDate date]];
    [dateFormatter release];
    _currentNoteBook.noteCreateTimeStamp = dateStr;
    
    
    if ((_currentNoteBook.image &&![_currentNoteBook.image isEqualToString:@""] )||( _currentNoteBook.content &&![_currentNoteBook.content isEqualToString:@""])) {
        [_noteTextField resignFirstResponder];
        [NoteBookManager sharedManager].gramarId = _currentGrammar.grammarId;
        [[NoteBookManager sharedManager] addNote:_currentNoteBook];
        RELEASE_SAFELY(_currentNoteBook);
        _currentNoteBook = [[Note alloc] init];
        [_detailTableView reloadData];
        _noteTextField.text = @"";
        [self updateNoteButton];
        [_camerButton setImage:[UIImage imageNamed:@"addphoto_btn.png"] forState:UIControlStateNormal];
        _isCaptured = NO;
        [GrammarManager sharedManager].grammarType = @"review";
        _currentGrammar.state = @"0";
        [[GrammarManager sharedManager] addGrammar:_currentGrammar];
        
    }else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请填写笔记或者拍照" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        [alertView release];
    }
}
#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    _addNoteView.bottom = SCREEN_HEIGHT -70;
}

#pragma mark - UIImagePicker
- (void)showCameraCaptureViewWithType:(int)type
{
    
    UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
    
    ITTDINFO(@"note text %@",_noteTextField.text);
    if (type == UIImagePickerControllerSourceTypeCamera) {
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            NSLog(@"抱歉, 该设备不支持拍照.");
            return;
        }
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        
    }else {
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }

    imagePickerController.allowsEditing = NO;
    imagePickerController.delegate = self;
    [self.navigationController presentModalViewController:imagePickerController animated:YES];
    [imagePickerController release];
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *dateStr = [dateFormatter stringFromDate:[NSDate date]];
    [dateFormatter release];
    _currentNoteBook.image = dateStr;
    NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];

    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage* editedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        //对图片进行处理
        UIImage *image = [self scaleAndRotateImage:editedImage];
        
        [[ITTImageCacheManager sharedManager] saveImage:image withUrl:_currentNoteBook.image];
        [_camerButton setImage:image forState:UIControlStateNormal];
        _isCaptured = YES;
    }
    
    [picker dismissModalViewControllerAnimated:YES];
    [self performSelector:@selector(tapKeepNoteButton:)];

}

- (UIImage *)scaleAndRotateImage:(UIImage *)image {
	static int kMaxResolution = 640;
	
	CGImageRef imgRef = image.CGImage;
	CGFloat width = CGImageGetWidth(imgRef);
	CGFloat height = CGImageGetHeight(imgRef);
	
	CGAffineTransform transform = CGAffineTransformIdentity;
	CGRect bounds = CGRectMake(0, 0, width, height);
	if (width > kMaxResolution || height > kMaxResolution) {
		CGFloat ratio = width/height;
		if (ratio > 1) {
			bounds.size.width = kMaxResolution;
			bounds.size.height = bounds.size.width / ratio;
		} else {
			bounds.size.height = kMaxResolution;
			bounds.size.width = bounds.size.height * ratio;
		}
	}
	
	CGFloat scaleRatio = bounds.size.width / width;
	CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
	CGFloat boundHeight;
	
	UIImageOrientation orient = image.imageOrientation;
    
	switch(orient) {
		case UIImageOrientationUp:
			transform = CGAffineTransformIdentity;
			break;
		case UIImageOrientationUpMirrored:
			transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
			transform = CGAffineTransformScale(transform, -1.0, 1.0);
			break;
		case UIImageOrientationDown:
			transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
			transform = CGAffineTransformRotate(transform, M_PI);
			break;
		case UIImageOrientationDownMirrored:
			transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
			transform = CGAffineTransformScale(transform, 1.0, -1.0);
			break;
		case UIImageOrientationLeftMirrored:
			boundHeight = bounds.size.height;
			bounds.size.height = bounds.size.width;
			bounds.size.width = boundHeight;
			transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
			transform = CGAffineTransformScale(transform, -1.0, 1.0);
			transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
			break;
		case UIImageOrientationLeft:
			boundHeight = bounds.size.height;
			bounds.size.height = bounds.size.width;
			bounds.size.width = boundHeight;
			transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
			transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
			break;
		case UIImageOrientationRightMirrored:
			boundHeight = bounds.size.height;
			bounds.size.height = bounds.size.width;
			bounds.size.width = boundHeight;
			transform = CGAffineTransformMakeScale(-1.0, 1.0);
			transform = CGAffineTransformRotate(transform, M_PI / 2.0);
			break;
		case UIImageOrientationRight:
			boundHeight = bounds.size.height;
			bounds.size.height = bounds.size.width;
			bounds.size.width = boundHeight;
			transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
			transform = CGAffineTransformRotate(transform, M_PI / 2.0);
			break;
		default:
			[NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
	}
	
	UIGraphicsBeginImageContext(bounds.size);
	CGContextRef context = UIGraphicsGetCurrentContext();
	if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
		CGContextScaleCTM(context, -scaleRatio, scaleRatio);
		CGContextTranslateCTM(context, -height, 0);
	} else {
		CGContextScaleCTM(context, scaleRatio, -scaleRatio);
		CGContextTranslateCTM(context, 0, -height);
	}
	CGContextConcatCTM(context, transform);
	CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
	UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	return imageCopy;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissModalViewControllerAnimated:YES];
}

#pragma mark - UITableView
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_tableViewType == DetailTableViewStyleTeach) {
        return 40;
    }else
        return 0;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_tableViewType == DetailTableViewStyleTeach) {
            if (_currentRowHeight > 0) {
                return _currentRowHeight;
            }else return 0; 
    }else{
            NoteBookCell *cell = (NoteBookCell*)[self tableView:_detailTableView cellForRowAtIndexPath:indexPath];
            return [cell getCellHeight];
    }    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_tableViewType == DetailTableViewStyleTeach) {
        return [_teachArray count];
    }else
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_tableViewType == DetailTableViewStyleTeach) {
        if (section == _selectedSection)
        {
            return 1;
        }
    }else if(_tableViewType == DetailTableViewStyleNote){
        [NoteBookManager sharedManager].gramarId = _currentGrammar.grammarId;
        return [[NoteBookManager sharedManager].notes count];
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (_tableViewType == DetailTableViewStyleTeach) {
        DetailHeaderView *headerView = [DetailHeaderView loadFromXib];
        headerView.delegate = self;
        [headerView setViewWithGrammarExplain:[_teachArray objectAtIndex:section]];
        headerView.section = section;
        if (section %2) {
            headerView.backgroundColor = [UIColor colorWithRed:234/255.0 green:228/255.0 blue:218/255.0 alpha:1.0];
        }else {
            headerView.backgroundColor = [UIColor colorWithRed:217/255.0 green:208/255.0 blue:195/255.0 alpha:1.0];
        }
        return headerView;
    }else return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_tableViewType == DetailTableViewStyleTeach) {
        NSString *cellIdentifier = @"TeachKnowledgeCell";
        _teachKnowledgeCell = (TeachKnowledgeCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (_teachKnowledgeCell == nil) {
            _teachKnowledgeCell = [[ITTXibViewUtils loadViewFromXibNamed:cellIdentifier] retain];
        }
        
        if (!DATA_ENV.isLoadKnowledge) {
            
            [_teachKnowledgeCell setCellWithKnowledge:[_teachArray objectAtIndex:_selectedSection] WithRefresh:YES];
        }else {
            [_teachKnowledgeCell setCellWithKnowledge:[_teachArray objectAtIndex:_selectedSection] WithRefresh:NO];
        }
        _teachKnowledgeCell.delegate = self;
        
        _teachKnowledgeCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return _teachKnowledgeCell;
    }else if (_tableViewType == DetailTableViewStyleNote) {
        NSString *cellIdentifier = @"NoteBookCell";
        NoteBookCell* cell = (NoteBookCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [ITTXibViewUtils loadViewFromXibNamed:cellIdentifier];
        }
        [NoteBookManager sharedManager].gramarId = _currentGrammar.grammarId;
        Note *noteBook = [[NoteBookManager sharedManager].notes objectAtIndex:indexPath.row];
        [cell setCellWithNote:noteBook];
        cell.delegate = self;
        cell.cellRow = indexPath.row;
        cell.contentView.backgroundColor = [UIColor whiteColor];
        if (indexPath.row %2) {
            cell.contentView.backgroundColor = [UIColor colorWithRed:234/255.0 green:228/255.0 blue:218/255.0 alpha:1.0];
        }else {
            cell.contentView.backgroundColor = [UIColor colorWithRed:217/255.0 green:208/255.0 blue:195/255.0 alpha:1.0];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    return nil;
}


#pragma mark - NoteBookCellDelegate
- (void)selectNoteBook:(Note *)noteBook
{
    [self enlargeTheImage:noteBook];
}

- (void)tapMoreOption:(Note *)noteBook withIndex:(NSInteger)index
{
    _deleteIndex = index;
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"删除", nil];
    actionSheet.tag = 1100;
    [actionSheet showInView:self.view];
    [actionSheet release];
}

#pragma mark - TeachKnowledgeCellDelegate
- (void)loadIsDoneWitHeight:(CGFloat)height
{
    DATA_ENV.isLoadKnowledge = TRUE;
    _currentRowHeight = height;

    if (_selectedSection < [_teachArray count])
    {
//        [_detailTableView beginUpdates];
        [_detailTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:0 inSection:_selectedSection], nil] withRowAnimation:UITableViewRowAnimationFade];
//        [_detailTableView endUpdates];
    }
    
}

- (void)didSelectImageView:(NSString *)imageUrl
{
    [self.view addSubview:_bgView];
    CGFloat height = (is4InchScreen()?SCREEN_HEIGHT_OF_IPHONE5-20:SCREEN_HEIGHT_OF_IPHONE4);
    ITTImageZoomableView *imageZoomView = [[ITTImageZoomableView alloc] initWithFrame:CGRectMake(0, 0, 320, height)];
    [self.view addSubview:imageZoomView];
    imageZoomView.alpha = 0;
    imageZoomView.tapDelegate = self;
    [imageZoomView displayImage:((ITTImageInfo*)imageUrl)];
    [UIView animateWithDuration:0.3f animations:^{
        imageZoomView.alpha = 1;
    } completion:^(BOOL finished) {
        
        [imageZoomView release];
    }];
    
}

- (void)imageZoomableViewSingleTapped:(ITTImageZoomableView*)imageZoomableView
{
    [UIView animateWithDuration:0.3f animations:^{
        imageZoomableView.alpha = 0;
    } completion:^(BOOL finished) {
        [imageZoomableView removeFromSuperview];
        [_bgView removeFromSuperview];
    }];
}
#pragma mark - HeaderViewDelegate

- (void)headerViewDidTapAtIndex:(NSUInteger)index
{
    if (_tableViewType == DetailTableViewStyleNote) {
        return;
    }
    if (_selectedSection == index)
    {
        DATA_ENV.isLoadKnowledge = TRUE;
        _selectedSection = [_teachArray count];
        [_detailTableView reloadSections:[NSIndexSet indexSetWithIndex:index] withRowAnimation:UITableViewRowAnimationFade];
    }
    else
    {
        if (_selectedSection < [_teachArray count])
        {
            NSUInteger lastSelectedSection = _selectedSection;
            _selectedSection = [_teachArray count];
            [_detailTableView reloadSections:[NSIndexSet indexSetWithIndex:lastSelectedSection] withRowAnimation:UITableViewRowAnimationFade];
        }
        DATA_ENV.isLoadKnowledge = FALSE;
        _selectedSection = index;
        [_detailTableView reloadSections:[NSIndexSet indexSetWithIndex:_selectedSection]withRowAnimation:UITableViewRowAnimationFade];
    }
}

#pragma mark - ITTPullTableViewDelegate

- (void)pullTableViewDidTriggerRefresh:(ITTPullTableView *)pullTableView
{
//    [self hideUpdateView];
    
    //[self getNewsListDataRequest];
//    [self getExplainDataRequest];
    if (isReachability) {
        [_detailTableView setRefreshViewHidden:NO];
        [self syncExplainDataRequest];
        [self updateNowState];
    }else {
        [self noNetWorkState];
        [self loadMoreDataDone];
        [self performSelector:@selector(refreshDataDone) withObject:nil afterDelay:1.0];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请查看网络连接" delegate:nil cancelButtonTitle:@"确定"otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
    
}

- (void)pullTableViewDidTriggerLoadMore:(ITTPullTableView *)pullTableView
{
    [_detailTableView setLoadMoreViewHidden:YES];
//    [self loadMoreNewsListDataRequest];
}

- (void)loadMoreDataDone
{
    /*
     *Code to actually load more data goes here.
     */
    _detailTableView.pullTableIsLoadingMore = NO;
}

- (void)refreshDataDone
{
    /*
     *Code to actually refresh goes here.
     */
    _detailTableView.pullLastRefreshDate = [NSDate date];
    _detailTableView.pullTableIsRefreshing = NO;
}

@end
